/*
  学习目标：新增
*/

import React, { Component } from 'react';
import './index.css';

export default class App extends Component {
  state = {
    username: '',
    content: '',
    list: [
      {
        id: 1,
        username: '思聪',
        content: '想你的夜',
      },
      {
        id: 2,
        username: '马芸',
        content: '我对钱不感兴趣',
      },
      {
        id: 3,
        username: '王简林',
        content: '实现一个小目标',
      },
    ],
  };

  handleChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  handleDelById = (id) => {
    const { list } = this.state;
    const newList = list.filter((item) => item.id !== id);

    this.setState({ list: newList });
  };
  handleClear = () => {
    this.setState({
      list: [],
    });
  };

  // 1. 定义方法

  handleAdd = (e) => {
    e.preventDefault();
    // 3. setState更新
    const { username, content, list } = this.state;

    this.setState({
      list: [{ id: Date.now(), username, content }, ...list],
      content: '',
      username: '',
    });
  };

  render() {
    const { list, username, content } = this.state;
    return (
      <div className="app">
        <form>
          <input
            name="username"
            value={username}
            onChange={this.handleChange}
            className="user"
            type="text"
            placeholder="请输入评论人"
          />
          <br />
          <textarea
            name="content"
            onChange={this.handleChange}
            value={content}
            className="content"
            cols="30"
            rows="10"
            placeholder="请输入评论内容"
          />
          <br />
          <button
            // 2. 绑定事件
            onClick={this.handleAdd}
          >
            发表评论
          </button>
          <button onClick={this.handleClear} type="button">
            清空评论
          </button>
        </form>

        {!list.length ? (
          <div>暂无数据</div>
        ) : (
          <ul>
            {list.map((item) => {
              return (
                <li key={item.id}>
                  <h3>评论人: {item.username}</h3>
                  <p>评论内容：{item.content}</p>
                  <button onClick={() => this.handleDelById(item.id)}>删除</button>
                </li>
              );
            })}
          </ul>
        )}
      </div>
    );
  }
}
